import { useLocation, useRoutes } from "react-router-dom";
import routes from "./routes.js";
import { useEffect, useState } from "react";
import { useSetupRouterTitleGuard } from "./title-guard.js";
import { cloneDeep } from "lodash";
import nProgress from "nprogress";

const RouterView = () => {
  //绑定进度条
  useState(nProgress.start());

  useEffect(() => {
    nProgress.done();
    return () => {
      nProgress.start();
    };
  });

  //滚动到顶部
  useEffect(() => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: "smooth",
    });
  }, []);

  useEffect(() => {
    const onBeforeUnload = () => {
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: "auto",
      });
    };

    window.addEventListener("beforeunload", onBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", onBeforeUnload);
    };
  }, []);
  const newRoutes = cloneDeep(routes);
  //绑定标题
  useSetupRouterTitleGuard(newRoutes);
  return <>{useRoutes(newRoutes)}</>;
};

export default RouterView;
